package com.qst.order.config;


import com.qst.order.utils.Result;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler implements ErrorController {

    // 处理404异常
    @ExceptionHandler(NoHandlerFoundException.class)
    public ResponseEntity<Map<String, Object>> handle404Error(HttpServletRequest request) {
        Map<String, Object> body = Map.of(
                "code", 404,
                "message", "请求的资源不存在",
                "path", request.getRequestURI()
        );
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(body);
    }

    // 处理空指针异常
    @ExceptionHandler(NullPointerException.class)
    public ResponseEntity<?> handleNPE(NullPointerException ex) {
        log.error("空指针异常: ", ex);
        return ResponseEntity.badRequest().body("请求参数不完整");
    }

    // 处理参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, Object>> handleValidationExceptions(MethodArgumentNotValidException ex) {
        BindingResult result = ex.getBindingResult();
        Map<String, Object> errorMap = new HashMap<>();
        errorMap.put("code", 400);
        errorMap.put("message", "参数校验失败");

        Map<String, String> fieldErrors = new HashMap<>();
        for (FieldError error : result.getFieldErrors()) {
            fieldErrors.put(error.getField(), error.getDefaultMessage());
        }
        errorMap.put("errors", fieldErrors);

        // 记录校验错误日志
        log.warn("参数校验失败: {}", ex.getMessage());
        return ResponseEntity.badRequest().body(errorMap);
    }

    // 处理其他未捕获的异常
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Map<String, Object>> handleGlobalError(HttpServletRequest request, Exception ex) {
        // 记录完整错误日志
        log.error("服务器内部错误 - 请求路径: " + request.getRequestURI(), ex);

        // 生产环境不应返回详细错误信息
        Map<String, Object> body = new HashMap<>();
        body.put("code", 500);
        body.put("message", "服务器内部错误");

        // 如果是开发环境，可以添加更多信息
        if (Arrays.asList(
                "localhost",
                "127.0.0.1",
                "0:0:0:0:0:0:0:1" // IPv6 localhost
        ).contains(request.getRemoteAddr())) {
            body.put("error", ex.getClass().getSimpleName());
            body.put("message", ex.getMessage());
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(body);
    }
    @ExceptionHandler(RuntimeException.class)
    public Result<Void> handleRuntimeException(RuntimeException e) {
        String message = e.getMessage();

        if (message.contains(":")) {
            message = message.split(":")[1]; // 取 "余额不足，请充值"
            log.info("异常{}",message);
        }
        return Result.error(message);
    }
}